﻿<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Wilson的聊天室</title>
    <link rel="icon" href="./static/img/chat.ico" type="image/x-icon"/>
    <link rel="stylesheet" type="text/css" href="./static/css/chatroom.css">
    <link rel="stylesheet" type="text/css" href="./static/css/common/layui.css">
    <link rel="stylesheet" type="text/css" href="./static/css/common/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="./static/css/common/fileinput.min.css">
</head>
<script type="text/javascript" src="./static/js/common/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="./static/js/common/jquery.actual.min.js"></script>
<script type="text/javascript" src="./static/js/common/bootstrap.min.js"></script>
<script type="text/javascript">
    let userId;
    let socket;
    let sentMessageMap;
    let senderId;
    let receiverId;
    let msgType;

    let ws = {
        register: function () {
            if (!window.WebSocket) {
                return;
            }
            if (socket.readyState === WebSocket.OPEN) {
                var data = {
                    "userId": userId,
                    "type": "REGISTER"
                };
                socket.send(JSON.stringify(data));
            } else {
                alert("Websocket连接没有开启！");
            }
        },
        sendPrivateChatMsg: function (fromUser, toUser, content) {
            if (socket.readyState === WebSocket.OPEN) {
                let data = {
                    "msgType": msgType,
                    "fromUser": fromUser,
                    "toUser": toUser,
                    "content": content
                };
                socket.send(JSON.stringify(data));
            } else {
                alert("Websocket连接没有开启!");
            }
        },
        sendGroupChatMsg: function (roomId, fromUser, content) {
            if (socket.readyState === WebSocket.OPEN) {
                let data = {
                    "roomId": roomId,
                    "msgType": msgType,
                    "fromUser": fromUser,
                    "content": content
                };
                console.log("send:" + data);
                socket.send(JSON.stringify(data));
            } else {
                alert("Websocket连接没有开启!");
            }
        },
        remove: function () {
            socket.close();
        }
    };
    $(document).ready(function () {
        $(".sendBtn").click(function () {
            const content = $("#dope").val();
            msgType = getUrlParam("msgType");
            let result;
            switch (msgType) {
                case "GroupChat":
                    senderId = getUrlParam("fromUser");
                    roomId = getUrlParam("roomId");
                    result = ws.sendGroupChatMsg(roomId, senderId, content);
                    $("#dope").val("");
                    break;
                case "PrivateChat":
                    senderId = getUrlParam("fromUser");
                    receiverId = getUrlParam("toUser");
                    result = ws.sendPrivateChatMsg(senderId, receiverId, content);
                    $("#content").append("<br/>me: " + content);
                    $("#dope").val("");
                    break;
                default:
                    break;
            }
        });
    });

    //获取url中的参数
    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]);
        return null; //返回参数值
    }

    function randomString(length) {
        length = length || 32;
        let t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
            a = t.length,
            n = "";
        for (let i = 0; i < length; i++) n += t.charAt(Math.floor(Math.random() * a));
        return n
    }

    if (!window.WebSocket) {
        window.WebSocket = window.MozWebSocket;
    }
    if (window.WebSocket) {
        let params;
        if (getUrlParam("msgType") === "PrivateChat") {
            params = "?fromUser=" + getUrlParam("fromUser") + "&toUser=" + getUrlParam("toUser") + "&msgType=PrivateChat";
        } else if (getUrlParam("msgType") === "GroupChat") {
            let user = getUrlParam("fromUser") === null ? randomString(6) : getUrlParam("fromUser");
            let roomId = getUrlParam("roomId");
            params = "?msgType=GroupChat&fromUser=" + user + "&roomId=" + roomId;
        } else {
            params = "?msgType=null";
        }
        socket = new WebSocket("ws://localhost:9000/chat" + params);
        socket.onmessage = function (event) {
            console.log("on message:" + event.data);
            let resp;
            let msgType = getUrlParam("msgType") == null ? "GroupChat" : getUrlParam("msgType");
            switch (msgType) {
                case "GroupChat":
                    senderId = getUrlParam("fromUser");
                    resp = $.parseJSON(event.data);
                    if (resp.code === 200) {
                        let data = resp.data;
                        if (data.fromUser === senderId) {
                            $("#content").append("<br/>me: " + data.content);
                        } else {
                            $("#content").append("<br/>" + data.fromUser + ": " + data.content);
                        }
                    } else {
                        console.log("resp.msg:" + resp.msg);
                    }
                    break;
                case "PrivateChat":
                    senderId = getUrlParam("fromUser");
                    resp = $.parseJSON(event.data);
                    if (resp.code === 200) {
                        let data = resp.data;
                        if (data.toUser === senderId) {
                            $("#content").append("<br/>" + data.fromUser + ": " + data.content);
                        }
                    } else {
                        console.log("resp.msg:" + resp.msg);
                    }
                    break;
                default:
                    break;
            }
        };
        socket.onopen = function () {
            console.log("websocket connect success");
        };
        socket.onclose = function (event) {
            console.log("websocket close");
            console.log(event);
        };
    } else {
        alert("您的浏览器不支持WebSocket！");
    }</script>

<body>
<div class="qqBox">
    <div class="BoxHead">
        <div class="headImg">
            <img id="avatarUrl" src="static/img/avatar/Member001.jpg"/>
        </div>
        <div id="username" class="internetName"></div>
    </div>
    <div class="context">
        <div class="conRight">
            <div class="Righthead">
                <div class="headName"></div>
            </div>
        </div>
        <div id="content"></div>
    </div>

    <div class="inputBox">
        <!--            <div class="inputBox">-->
        <textarea id="dope"
                  style="overflow:hidden;width: 100%;height: 75px;border-bottom: none;border-left: none;border-right: none; outline: none;"
                  name="" rows="" cols=""></textarea>
        <button title="按下回车可发送" class="sendBtn">发送</button>
    </div>
</div>


</body>
</html>
